﻿using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
using System.Web;
using System.Web.Services;
using HiTeachers.Utilities;

namespace HiTeachers.Web
{
    /// <summary>
    /// Summary description for $codebehindclassname$
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    public class ImageScale : IHttpHandler
    {
        public bool IsReusable
        {
            get { return false; }
        }

        public void ProcessRequest(HttpContext context)
        {
            try
            {
                //get the filename
                string file = context.Request.QueryString["image"];

                //get the desired maximum width/height of the image
                int width = int.Parse(context.Request.QueryString["width"]);
                int height = int.Parse(context.Request.QueryString["height"]);

                if (string.IsNullOrEmpty(file)) file = "images/noimage.jpg";

                string ext = Path.GetExtension(file);
                string pathFile = HttpContext.Current.Server.MapPath("/");
                if (file.StartsWith("/")) file = file.Substring(1, file.Length - 1);

                pathFile = Path.Combine(pathFile, file);
                RenderImage(context, pathFile, ext, width, height, true);
            }
            catch (Exception ex)
            {
                context.Response.Clear();
                context.Response.End();

                Logger.Error(ex);
                throw;
            }
        }

        private void RenderImage(HttpContext context, string path, string ext)
        {
            RenderImage(context, path, ext, -1, -1, false);
        }

        private static void RenderImage(HttpContext context, string path, string ext, int width, int height, bool doResize)
        {
            context.Response.Clear();

            try
            {
                if (File.Exists(path))
                {
                    context.Response.ContentType = "image/jpeg";

                    using (Stream imgStream = File.Open(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
                    {
                        if (doResize)
                        {
                            //create the resized image and stream it to the response
                            using (Bitmap b = Resize(imgStream, width, height))
                            {
                                b.Save(context.Response.OutputStream, ImageFormat.Jpeg);
                            }
                        }
                        else
                        {
                            Bitmap b = new Bitmap(imgStream);
                            b.Save(context.Response.OutputStream, ImageFormat.Jpeg);
                            b.Dispose();

                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.Error(ex);
                throw;
            }
        }

        private void ReturnUploadedFile(HttpContext c)
        {

            string imagePath = c.Request["Path"];
            if (imagePath != null)
            {
                // ReSharper disable PossibleNullReferenceException
                string ext = Path.GetExtension(imagePath).ToLower();
                // ReSharper restore PossibleNullReferenceException
                RenderImage(c, imagePath, ext, -1, -1, false);
            }

        }

        private static Bitmap Resize(Stream sourceImage, int maxWidth, int maxHeight)
        {
            Bitmap b = null;

            try
            {
                using (Image i = Image.FromStream(sourceImage))
                {
                    int _maxWidth = (maxWidth > 0) ? maxWidth : i.Width;
                    int _maxHeight = (maxHeight > 0) ? maxHeight : i.Height;
                    double _scaleWidth = (double)_maxWidth / (double)i.Width;
                    double _scaleHeight = (double)_maxHeight / (double)i.Height;
                    double _scale = (_scaleHeight < _scaleWidth) ? _scaleHeight : _scaleWidth;
                    _scale = (_scale > 1) ? 1 : _scale;

                    int _newWidth = (int)(_scale * i.Width);
                    int _newHeight = (int)(_scale * i.Height);

                    b = new Bitmap(_newWidth, _newHeight);

                    using (Graphics g = Graphics.FromImage(b))
                    {
                        g.CompositingQuality = CompositingQuality.HighQuality;
                        g.SmoothingMode = SmoothingMode.HighQuality;
                        g.InterpolationMode = InterpolationMode.HighQualityBicubic;
                        g.DrawImage(i, new Rectangle(0, 0, _newWidth, _newHeight));
                        g.Save();
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.Error(ex);
                throw;
            }
            return b;
        }
    }
}
